<?php

class DbTools
{
    private static $conn;
    private static $host = '127.0.0.1';
    private static $user = 'root';
    private static $password = 'root';
    private static $database = 'newbank04';

    public static function init($host = '', $user = '', $password = '', $database = '')
    {
        if (!empty($host)) {
            self::$host = $host;
        }
        if (!empty($user)) {
            self::$user = $user;
        }
        if (!empty($password)) {
            self::$password = $password;
        }
        if (!empty($database)) {
            self::$database = $database;
        }

        self::$conn = new mysqli();

        self::$conn->connect(self::$host, self::$user, self::$password, self::$database);
        if (!empty(self::$conn->connect_error)) {
            echo '数据库连接失败：' . self::$conn->connect_error;
            die;
        }
    }

    public static function select($sql)
    {
        $data = [];
        $result = self::$conn->query($sql);
        if (empty(self::$conn->error)) {
            while (true) {
                $row = $result->fetch_assoc();
                if (empty($row)) {
                    break;
                }
                $data[] = $row;
            }
        }
        $result->close();
        return $data;
    }

    public static function noSelect($sql)
    {
        $result = self::$conn->query($sql);
        if ($result) {
            if (self::$conn->affected_rows > 0) {
                return [
                    'status' => true,
                    'message' => ''
                ];
            } else {
                return [
                    'status' => false,
                    'message' => '影响力为0'
                ];
            }
        } else {
            return [
                'status' => false,
                'message' => self::$conn->error
            ];
        }
    }

    public static function close()
    {
        self::$conn->close();
    }
}
